package su.product.service.impl;

import java.util.List;

import net.kuakao.core.dto.PagerDTO;

import org.springframework.beans.factory.annotation.Autowired;

import su.base.Constants;
import su.product.dao.ICateDAO;
import su.product.dao.IMaterialDAO;
import su.product.entity.Cate;
import su.product.entity.Material;
import su.product.service.MaterialService;

public class MaterialServiceImpl implements MaterialService {
	
	@Autowired
	private IMaterialDAO materialDAO;

	@Autowired
	private ICateDAO cateDAO;
	
	public List<Material> getMaterialsByCate(PagerDTO s){
		List<Material> list = null;
		try {
			list = materialDAO.queryByPage(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public Material getMaterialById(int id){
		Material one = null;
		try {
			one = materialDAO.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return one;
	}

	public void saveMaterial(Material o) throws Exception {
		o.setStatus(Constants.STATUS_ENABLE);
		if(o.getId()==0){
			//添加
			materialDAO.insert(o);
			//修改分类的原料数量
			cateDAO.updateProductNum(o.getCateid(), true);
		}else{
			materialDAO.update(o);
		}
		
	}
	
	public void removeMaterial(int id) throws Exception {
		materialDAO.remove(id);
	}

	public void updateMaterialCate(int productId,int oldCateId,int newCateId)throws Exception{
		//验证
		Cate newCate = cateDAO.getById(newCateId);
		if(newCate==null)throw new Exception("未找到id为"+newCateId+"的目标分类");
		//修改分类
		materialDAO.updateProductCate(productId, oldCateId, newCateId);
		//修改原分类下产品数
		cateDAO.updateProductNum(oldCateId, false);
		//修改新分类下产品数
		cateDAO.updateProductNum(newCateId, true);
	}
	
}

